'use strict';

const db = uniCloud.database();
const dbCmd = db.command;

exports.main = async (event, context) => {
  console.log('【debugIncome】调试收入结算:', event);
  
  const { taskId, receiverId } = event;
  
  try {
    // 1. 查找收入记录
    const incomeRes = await db.collection('task_income_records')
      .where({ task_id: taskId })
      .get();
    
    console.log('【debugIncome】找到收入记录:', incomeRes.data);
    
    if (incomeRes.data.length === 0) {
      return {
        code: 404,
        msg: '未找到收入记录',
        data: null
      };
    }
    
    const incomeRecord = incomeRes.data[0];
    
    // 2. 更新收入记录状态
    const updateResult = await db.collection('task_income_records')
      .doc(incomeRecord._id)
      .update({
        status: 'completed',
        receiver_id: receiverId,
        complete_time: Date.now()
      });
    
    console.log('【debugIncome】收入记录更新结果:', updateResult);
    
    // 3. 更新用户余额
    const balanceResult = await db.collection('uni-id-users')
      .doc(receiverId)
      .update({
        balance: dbCmd.inc(incomeRecord.reward_amount)
      });
    
    console.log('【debugIncome】余额更新结果:', balanceResult);
    
    // 4. 记录支付记录
    const paymentResult = await db.collection('payment_records').add({
      payment_id: `INCOME_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      user_id: receiverId,
      amount: incomeRecord.reward_amount,
      payment_method: 'system',
      type: 'task_income',
      status: 'success',
      task_info: { task_id: taskId },
      create_time: Date.now(),
      desc: '任务完成收入（手动调试）'
    });
    
    console.log('【debugIncome】支付记录创建结果:', paymentResult);
    
    return {
      code: 200,
      msg: '收入结算成功',
      data: {
        taskId,
        receiverId,
        rewardAmount: incomeRecord.reward_amount,
        incomeRecordUpdated: updateResult.updated,
        balanceUpdated: balanceResult.updated,
        paymentRecordCreated: paymentResult.id
      }
    };
    
  } catch (error) {
    console.error('【debugIncome】调试失败:', error);
    return {
      code: 500,
      msg: '调试失败',
      error: error.message
    };
  }
};